package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.xcity.game.battle.res.ResStage;
import com.xcity.game.battle.res.ResStageManager;
import com.xcity.game.battle.res.ResStageTypeInfo;

import naga.x.util.StringUtils;

public class ResStagesTypeHandler extends BaseTypeHandler<ResStageManager>{

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, ResStageManager parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter != null? parameter.toString() : "[]");
	}

	@Override
	public ResStageManager getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public ResStageManager getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public ResStageManager getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}

	public static ResStageManager parse(String json){
		if(StringUtils.isEmpty(json)){
			return new ResStageManager(null, null, null);
		}
		String[] strs = StringUtils.split(json, ";");
		if(strs.length > 1){
			ResStageTypeInfo typeinfo = (ResStageTypeInfo) JSON.parseObject(strs[1], ResStageTypeInfo.class);
			return new ResStageManager(null, JSON.parseArray(strs[0], ResStage.class), typeinfo);
		}
		return new ResStageManager(null, JSON.parseArray(strs[0], ResStage.class), null);
	}
}
